<template>
  <div class="main-container">
    <div class="main-content">
      <div class="common-functions">
        <h2>常用功能</h2>
        <div class="function-buttons">
          <button
              v-for="func in commonFunctions"
              :key="func"
              @click="handleFunctionClick(func)"
              class="function-button"
          >
            {{ func }}
          </button>
        </div>
      </div>

      <div class="content-container">
        <!-- Todo container -->
        <div class="todo-container">
          <h2>待办理事务</h2>
          <div class="todo-scroll-container">
            <div class="calendar-and-tasks">
              <Calendar
                  @select-date="handleDateSelect"
                  :tasks="tasks"
              />
              <div class="today-tasks" v-if="selectedDate && tasks[selectedDate]">
                <div
                    v-for="(task, index) in tasks[selectedDate]"
                    :key="index"
                    class="task-item"
                >
                  <span class="task-time">{{ task.time }}</span>
                  <span class="task-content">{{ task.content }}</span>
                </div>
              </div>
            </div>
            <div class="add-task-container">
              <h3>添加事务</h3>
              <textarea
                  placeholder="例如：17:23 参加会议"
                  v-model="newTaskDescription"
                  class="task-input"
              ></textarea>
              <el-button
                  type="primary"
                  @click="handleAddTask"
                  :loading="isAddingTask"
              >
                添加
              </el-button>
            </div>
          </div>
        </div>

        <div class="semester-notifications-container">
          <h2>学期课程安排/通知公告</h2>
          <div class="semester-schedule-container">
            <div
                v-for="(month, index) in semesterMonths"
                :key="index"
                :class="['month-container', { clicked: clickedMonths.includes(index) }]"
                :style="{ backgroundColor: getMonthBackgroundColor(index) }"
                @click="handleMonthClick(index)"
            >
              <h3>{{ month }}</h3>
              <div v-if="getFilteredNotifications(month).length > 0" class="month-notifications">
                <div
                    v-for="(notification, i) in getFilteredNotifications(month)"
                    :key="i"
                    :class="['notification-item', { viewed: notification.viewed }]"
                    @click.stop="handleNotificationClick(notification, index, i)"
                >
                  <p>{{ notification.title }}</p>
                  <small>{{ notification.date }}</small>
                </div>
              </div>
              <div v-else class="no-results">
                无匹配结果
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="search-history-container">
      <h3>事务查询</h3>
      <p class="search-hint">输入内容，对过往事例快速定位</p>
      <el-input
          v-model="searchQuery"
          placeholder="搜索..."
          class="search-input"
          @keyup.enter="handleSearch"
          :disabled="isSearching"
      >
        <template #append>
          <el-button @click="handleSearch" :loading="isSearching">
            <el-icon><Search /></el-icon>
          </el-button>
        </template>
      </el-input>
      <div class="history-list">
        <div
            v-for="(record, index) in searchHistory"
            :key="index"
            class="history-item"
        >
          <div class="search-content">{{ record.query }}</div>
          <small class="search-time">搜索时间：{{ record.searchTime }}</small>
          <div class="search-answer">{{ record.answer }}</div>
          <small class="answer-time">回答时间：{{ record.answerTime }}</small>
          <div v-if="index < searchHistory.length - 1" class="divider"></div>
        </div>
      </div>
    </div>

    <NotificationModal
        v-if="showNotificationModal"
        :notification="currentNotification"
        @close="closeNotificationModal"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElButton, ElInput } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import Calendar from './Calendar.vue'
import NotificationModal from './NotificationModal.vue'
import { useCounterStore } from '@/stores/counter'

const counterStore = useCounterStore()

const commonFunctions = ref([
  '事务查询',
  '课程安排',
  '个人中心',
  '文档管理',
  '流程制定管理',
  '课程成绩分析',
  '培养方案',
  '资源搜索',
])

const newTaskDescription = ref('')
const selectedDate = ref<string | null>(null)
const isAddingTask = ref(false)

const searchQuery = ref('')
const isSearching = ref(false)

const showNotificationModal = ref(false)
const currentNotification = ref({
  title: '',
  date: '',
  type: '',
  content: '',
  attachments: [] as Array<{name: string, url: string}>
})

const tasks = computed(() => counterStore.tasks)
const searchHistory = computed(() => counterStore.searchHistory)
const semesterMonths = computed(() => counterStore.getAllMonths)
const clickedMonths = computed(() => counterStore.getClickedMonths)
const colors = computed(() => counterStore.getColors)
const monthlyNotifications = computed(() => counterStore.notion.monthlyNotifications)

onMounted(async () => {
  try {
    await counterStore.fetchTasks()
    await counterStore.fetchMonthlyNotifications()
  } catch (error) {
    ElMessage.error('初始化数据失败，请刷新重试')
  }
})


const handleFunctionClick = (func: string) => {
  ElMessage.info(`功能: ${func}`)
}

const handleDateSelect = (date: string) => {
  selectedDate.value = date
}

const handleAddTask = async () => {
  if (!selectedDate.value || !newTaskDescription.value.trim()) {
    ElMessage.warning('请选择日期并输入事务内容')
    return
  }

  const input = newTaskDescription.value.trim()
  const timeMatch = input.match(/^(\d{1,2}:\d{2})/)
  let time = ''
  let content = input

  if (timeMatch) {
    time = timeMatch[1]
    content = input.substring(time.length).trim()
  }

  isAddingTask.value = true
  try {
    await counterStore.addTask(selectedDate.value, {
      time: time || '未指定时间',
      content
    })
    newTaskDescription.value = ''
    ElMessage.success('事务添加成功')
  } catch (error) {
    ElMessage.error('事务添加失败')
  } finally {
    isAddingTask.value = false
  }
}

const handleMonthClick = (index: number) => {
  counterStore.addClickedMonth(index)
}

const getMonthBackgroundColor = (index: number) => {
  const month = semesterMonths.value[index]
  const notifications = monthlyNotifications.value[month]
  if (notifications && notifications.every(n => n.viewed)) {
    return '#f0f0f0'
  }
  return colors.value[index % colors.value.length]
}

const handleNotificationClick = async (
    notification: any,
    monthIndex: number,
    notificationIndex: number
) => {
  try {
    await counterStore.markNotificationAsRead(semesterMonths.value[monthIndex], notification.id)
    currentNotification.value = {
      title: notification.title,
      date: notification.date,
      type: notification.type,
      content: notification.content,
      attachments: notification.attachments || []
    }
    showNotificationModal.value = true
  } catch (error) {
    ElMessage.error('标记通知为已读失败')
  }
}

const closeNotificationModal = () => {
  showNotificationModal.value = false
}

const handleSearch = async () => {
  if (!searchQuery.value.trim()) {
    ElMessage.warning('请输入搜索内容')
    return
  }

  isSearching.value = true
  try {
    await counterStore.search(searchQuery.value)
    searchQuery.value = ''
  } catch (error) {
    ElMessage.error('搜索失败')
  } finally {
    isSearching.value = false
  }
}

const getFilteredNotifications = (month: string) => {
  if (!searchQuery.value.trim()) {
    return monthlyNotifications.value[month] || []
  }

  const searchTerm = searchQuery.value.toLowerCase()
  const notifications = monthlyNotifications.value[month] || []

  return notifications.filter(notification => {
    return (
        notification.title.toLowerCase().includes(searchTerm) ||
        notification.content.toLowerCase().includes(searchTerm) ||
        notification.type.toLowerCase().includes(searchTerm))
  })
}

const filteredNotifications = computed(() => {
  const result: Record<string, any[]> = {}
  for (const month of semesterMonths.value) {
    result[month] = getFilteredNotifications(month)
  }
  return result
})
</script>

<style scoped>
.main-container {
  display: flex;
  height: 100vh;
  padding: 20px;
  box-sizing: border-box;
  gap: 20px;
}

.main-content {
  flex: 3;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.common-functions {
  margin-bottom: 20px;
}

.common-functions h2 {
  font-size: 1.5em;
  margin-bottom: 10px;
  color: #333;
}

.function-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.function-button {
  background-color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease, box-shadow 0.3s ease;
  font-size: 1em;
  color: #333;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.function-button:hover {
  background-color: #f0f0f0;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}

.content-container {
  display: flex;
  gap: 20px;
  flex: 1;
  min-height: 0;
}

.todo-container {
  flex: 2;
  background-color: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  height: calc(100vh - 180px);
}

.todo-scroll-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
}

.todo-container h2 {
  font-size: 1.5em;
  margin-bottom: 20px;
  color: #333;
}

.calendar-and-tasks {
  display: flex;
  flex-direction: column;
  gap: 20px;
  flex-shrink: 0;
}

.today-tasks {
  padding: 15px;
  border-radius: 5px;
}

.task-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
  margin-bottom: 15px;
  padding: 10px;
  background-color: #e6f2ff;
  border-radius: 5px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.task-time {
  font-weight: bold;
  color: #333;
  font-size: 1.1em;
}

.task-content {
  color: #333;
  margin-left: 5px;
}

.add-task-container {
  margin-top: auto;
  padding: 20px 0;
  display: flex;
  flex-direction: column;
  gap: 10px;
  position: sticky;
  bottom: 0;
  background: white;
  z-index: 1;
}

.add-task-container h3 {
  font-size: 1.2em;
  margin-bottom: 10px;
  color: #333;
}

.task-input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  background-color: #f8f9fa;
  box-sizing: border-box;
  resize: none;
  min-height: 80px;
  font-size: 0.95em;
}

.task-input::placeholder {
  color: #999;
  font-style: italic;
}

.semester-notifications-container {
  flex: 3;
  background-color: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  overflow-y: auto;
  max-height: 80vh;
}

.semester-notifications-container h2 {
  font-size: 1.2em;
  margin-bottom: 20px;
  color: #333;
}

.semester-schedule-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.month-container {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  text-align: left;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.month-container h3 {
  margin: 0 0 10px;
  font-size: 1.2em;
}

.month-notifications {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.notification-item {
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.notification-item.viewed {
  background-color: #f0f0f0;
}

.notification-item:hover {
  background-color: #f0f0f0;
}

.no-results {
  padding: 10px;
  color: #999;
  font-style: italic;
}

.search-history-container {
  flex: 1;
  background-color: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.search-history-container h3 {
  font-size: 1.2em;
  margin-bottom: 10px;
  color: #333;
}

.search-hint {
  font-size: 0.9em;
  color: #999;
  margin-bottom: 15px;
}

.search-input {
  width: 100%;
  margin-bottom: 20px;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.history-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.search-content {
  font-weight: bold;
  color: #333;
}

.search-time {
  color: #999;
  font-size: 0.8em;
}

.search-answer {
  color: #666;
}

.answer-time {
  color: #999;
  font-size: 0.8em;
}

.divider {
  height: 1px;
  background-color: #eee;
  margin: 10px 0;
}
</style>